package com.wnxy.sddfp.system.mq;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wnxy.sddfp.common.constant.MQConstant;
import com.wnxy.sddfp.common.exception.Assert;
import com.wnxy.sddfp.common.model.dto.bank.BankCardRequestDto;
import com.wnxy.sddfp.common.result.enums.impl.BusinessCode;
import com.wnxy.sddfp.system.entity.UserCard;
import com.wnxy.sddfp.system.entity.UserDetail;
import com.wnxy.sddfp.system.service.IUserCardService;
import com.wnxy.sddfp.system.service.IUserDetailService;
import com.wnxy.sddfp.system.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class CardResultConsumer {

    @Autowired
    private IUserDetailService userDetailService;
    @Autowired
    private IUserCardService userCardService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MQConstant.SDDFP_CARD_QUEUE,durable = "true"),
            exchange = @Exchange(name = MQConstant.SDDFP_CARD_EXCHANGE,type = ExchangeTypes.TOPIC,durable = "true"),
            key = MQConstant.SDDFP_CARD_ROUTING
    ))
    public void handlerMsg(@Payload BankCardRequestDto bankCardRequestDto) {
        log.info("后台管理系统，消费绑卡结果消息：{}",bankCardRequestDto);
        // 修改user_detail表用户绑卡状态，设置为1表示绑卡成功
        userDetailService.update(
                Wrappers.lambdaUpdate(UserDetail.class)
                        .set(UserDetail::getCardBindStatus,1)
                        .eq(UserDetail::getReqCode,bankCardRequestDto.getReqCode())
        );
        // 根据请求流水号查询用户id
        Long userId = getUserId(bankCardRequestDto.getReqCode());
        // 修改user_card表银行卡相关信息
        userCardService.update(
                Wrappers.lambdaUpdate(UserCard.class)
                        .set(UserCard::getBankNo,bankCardRequestDto.getBankNo())
                        .set(UserCard::getBankTitle,bankCardRequestDto.getBankTitle())
                        .eq(UserCard::getUserId,userId)

        );
    }

    /**
     * 根据reqCode查询获取用户id
     */
    private Long getUserId(String reqCode) {
        UserDetail userDetail = userDetailService.getOne(
                Wrappers.lambdaQuery(UserDetail.class)
                        .select(UserDetail::getId)
                        .eq(UserDetail::getReqCode, reqCode)
        );
        Assert.error(userDetail == null, BusinessCode.USER_NOT_EXIST);
        return userDetail.getId();
    }
}
